<?PHP
#
#   FILE:  RegisterPortal.php
#
#   Part of the Metavus digital collections platform
#   Copyright 2004-2022 Edward Almasy and Internet Scout Research Group
#   http://metavus.net
#
# @scout:phpstan

namespace Metavus;

use XMLWriter;
use ScoutLib\ApplicationFramework;
use ScoutLib\Database;
use ScoutLib\Email;
use ScoutLib\StdLib;

# ----- EXPORTED FUNCTIONS ---------------------------------------------------

/** * Print the list that previews all the information sent by a registration.
*/
function PrintRegistrationInfo(): void
{
    $SysConfig = SystemConfiguration::getInstance();

    # general site info
    print("Software: Metavus ".METAVUS_VERSION."<br>\n");
    print("Site Name: <i>".$SysConfig->getString("PortalName")."</i><br>\n");
    print("Site URI: <i>".$_SERVER["SERVER_NAME"]
          .dirname($_SERVER["REQUEST_URI"])."</i><br>\n");
    print("Admin E-Mail: <i>".$SysConfig->getString("AdminEmail")."</i><br>\n");

    # configuration settings
    print("Default UI: ".$SysConfig->getString("DefaultActiveUI")."<br>\n");
    print("Current Theme: ".$SysConfig->getString("CurrentTheme")."<br>\n");
    print("Announcements: ".($SysConfig->getBool("AnnouncementsEnabled") ?
            "ENABLED" : "DISABLED")."<br>\n");
    print("Multiple UIs: ".($SysConfig->getBool("AllowMultipleUIsEnabled") ?
            "ENABLED" : "DISABLED")."<br>\n");
    print("Ratings: ".($SysConfig->getBool("ResourceRatingsEnabled") ?
            "ENABLED" : "DISABLED")."<br>\n");
    print("Search Update: ".($SysConfig->getBool("SearchDBEnabled") ?
            "ENABLED" : "DISABLED")."<br>\n");
    print("Recommender Update: ".($SysConfig->getBool("RecommenderDBEnabled") ?
            "ENABLED" : "DISABLED")."<br>\n");
    print("Search Logic: ".($SysConfig->getBool("SearchTermsRequired") ?
            "AND" : "OR")."<br>\n");

    # resources info
    $RFactory = new RecordFactory();
    $ResourceCount = $RFactory->getItemCount();

    print("Resource Count: ".$ResourceCount."<br>\n");
    $ReleasedResourceCount = count(
        $RFactory->filterOutUnviewableRecords(
            $RFactory->getItemIds(),
            User::getAnonymousUser()
        )
    );

    print("Released Count: ".$ReleasedResourceCount."<br>\n");
    $RatedResourceCount = $RFactory->getRatedRecordCount();
    print("Rating Count: ".$RatedResourceCount."<br>\n");

    $ClassFactory = new ClassificationFactory();
    $ClassCount = $ClassFactory->getItemCount();
    print("Classification Count: ".$ClassCount."<br>\n");

    $SampleCount = $RFactory->getItemCount(
        "INSTR(Description, '[--SAMPLE RECORD--]') > 0"
    );
    print("Sample Count: ".$SampleCount."<br>\n");

    $SearchEngine = new SearchEngine();
    $TermCount = $SearchEngine->searchTermCount();
    print("Search Term Count: ".$TermCount."<br>\n");

    # PHP configuration
    print("PHP Version: ".phpversion()."<br>\n");
    $Settings = array(
        "safe_mode",
        "register_globals",
        "max_execution_time",
        "memory_limit",
        "post_max_size",
        "file_uploads",
        "upload_max_filesize",
    );
    foreach ($Settings as $Setting) {
        $Value = ini_get($Setting);
        if ($Value === false) {
            $Value = "(unknown)";
        } elseif (!strlen($Value)) {
            $Value = "Off";
        } elseif ($Value == "1") {
            $Value = "On";
        }
        print("PHP ".$Setting.": ".$Value."<br>\n");
    }
    $PhpInfo = StdLib::getPhpInfo();
    $Val = $PhpInfo["gd"]["GD Version"][0]
            ?? $PhpInfo["gd"]["GD library Version"][0]
            ?? "unavailable";
    print("PHP GD version: ".$Val."<br>\n");
    $Val = $PhpInfo["gd"]["PNG Support"][0] ?? "unavailable";
    print("PHP GD PNG Support: ".$Val."<br>\n");
    $Val = $PhpInfo["gd"]["JPG Support"][0]
            ?? $PhpInfo["gd"]["JPEG Support"][0]
            ?? "unavailable";
    print("PHP GD JPG Support: ".$Val."<br>\n");
    $Val = $PhpInfo["gd"]["GIF Support"][0]
            ?? $PhpInfo["gd"]["GIF Create Support"][0]
            ?? "unavailable";
    print("PHP GD GIF Support: ".$Val."<br>\n");

    $DB = new Database();

    # operating environment
    print("MySQL Client Version: ".$DB->getClientVersion()."<br>\n");
    print("MySQL Server Version: ".$DB->getServerVersion()."<br>\n");
    print("MySQL Connection Type: ".$DB->getHostInfo()."<br>\n");
    print("HTTP Server: <i>".$_SERVER["SERVER_SOFTWARE"]."</i><br>\n");
    print("OS Stamp: <i>".$PhpInfo[""]["System"][0]."</i><br>\n");
}

# print current content of user-entered registration settings
function PrintContactName(): void
{
    print(SystemConfiguration::getInstance()->getString("ContactName"));
}

function PrintContactEmail(): void
{
    print(SystemConfiguration::getInstance()->getString("ContactEmail"));
}

function PrintOrganization(): void
{
    print(SystemConfiguration::getInstance()->getString("Organization"));
}

function PrintOrganizationType(): void
{
    print(SystemConfiguration::getInstance()->getString("OrganizationType"));
}

function PrintSiteType(): void
{
    print(SystemConfiguration::getInstance()->getString("SiteType"));
}

function PrintOkayToListSite(): void
{
    print(SystemConfiguration::getInstance()->getBool("OkayToListSite"));
}

function PrintCheckedIfOrganizationTypeIs(string $OrganizationType): void
{
    print((SystemConfiguration::getInstance()->getString("OrganizationType")
            == $OrganizationType) ? " checked" : "");
}

function PrintCheckedIfSiteTypeIs(string $SiteType): void
{
    print((SystemConfiguration::getInstance()->getString("SiteType")
            == $SiteType) ? " checked" : "");
}

function PrintCheckedIfOkayToListSite(): void
{
    print((SystemConfiguration::getInstance()->getBool("OkayToListSite")) ? " checked" : "");
}

/**
 * Generate content for registration email.
 * @param string $Comments optional comments provided by user.
 * @return string XML registration data.
 */
function getRegistrationXML($Comments): string
{
    $SysConfig = SystemConfiguration::getInstance();

    # create XML writer to use in generating content
    $XW = new XMLWriter();
    $XW->openMemory();
    $XW->startDocument("1.0", "UTF-8");
    $XW->setIndent(true);
    $XW->setIndentString("    ");

    # start registration element and add schema info as attributes
    $XW->startElement("registration");
    $XW->writeAttribute("xmlns", "http://scout.wisc.edu/XML/register_v1.0/");
    $XW->writeAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    $XW->writeAttribute("xsi:schemaLocation", "http://scout.wisc.edu/XML/register_v1.0/ "
        ."http://scout.wisc.edu/XML/schemas/register_v1.0.xsd");
    $XW->writeAttribute("schemaVersion", "1.0");

    # retrieve and add general site info
    $XW->writeElement("software", "Metavus ".METAVUS_VERSION);
    if ($SysConfig->isSet("PortalName")) {
        $XW->writeElement("sitename", $SysConfig->getString("PortalName"));
    }
    $XW->writeElement("siteuri", $_SERVER["SERVER_NAME"].dirname($_SERVER["REQUEST_URI"]));
    if ($SysConfig->isSet("AdminEmail")) {
        $XW->writeElement("adminemail", $SysConfig->getString("AdminEmail"));
    }
    if ($SysConfig->isSet("ContactName")) {
        $XW->writeElement("contactname", $SysConfig->getString("ContactName"));
    }
    if ($SysConfig->isSet("ContactEmail")) {
        $XW->writeElement("contactemail", $SysConfig->getString("ContactEmail"));
    }
    if ($SysConfig->isSet("Organization")) {
        $XW->writeElement("organization", $SysConfig->getString("Organization"));
    }
    if ($SysConfig->isSet("OrganizationType")) {
        $XW->writeElement("organizationtype", $SysConfig->getString("OrganizationType"));
    }
    if ($SysConfig->isSet("SiteType")) {
        $XW->writeElement("sitetype", $SysConfig->getString("SiteType"));
    }
    $XW->writeElement("okaytolistsite", ($SysConfig->getBool("OkayToListSite") ? "TRUE" : "FALSE"));
    $XW->writeElement("registeringuser", User::getCurrentUser()->Get("UserName"));

    # retrieve and add configuration settings
    $XW->startElement("configuration");
    if ($SysConfig->getString("DefaultActiveUI")) {
        $XW->writeElement("defaultui", $SysConfig->getString("DefaultActiveUI"));
    }
    if ($SysConfig->getString("CurrentTheme")) {
        $XW->writeElement("currenttheme", $SysConfig->getString("CurrentTheme"));
    }
    $XW->startElement("toggles");
    $XW->writeElement(
        "announcements",
        ($SysConfig->getBool("AnnouncementsEnabled") ? "ENABLED" : "DISABLED")
    );
    $XW->writeElement(
        "multipleuis",
        ($SysConfig->getBool("AllowMultipleUIsEnabled") ? "ENABLED" : "DISABLED")
    );
    $XW->writeElement(
        "ratings",
        ($SysConfig->getBool("ResourceRatingsEnabled") ? "ENABLED" : "DISABLED")
    );
    $XW->writeElement(
        "searchupdate",
        ($SysConfig->getBool("SearchDBEnabled") ? "ENABLED" : "DISABLED")
    );
    $XW->writeElement(
        "recommenderupdate",
        ($SysConfig->getBool("RecommenderDBEnabled") ? "ENABLED" : "DISABLED")
    );
    $XW->writeElement("searchlogic", ($SysConfig->getBool("SearchTermsRequired") ? "AND" : "OR"));
    $XW->endElement();
    $XW->endElement();

    # retrieve and add resource DB info
    $XW->startElement("datastatistics");
    $RFactory = new RecordFactory();
    $XW->writeElement("resourcecount", (string)$RFactory->getItemCount());
    $ReleasedResourceCount = count(
        $RFactory->filterOutUnviewableRecords(
            $RFactory->getItemIds(),
            User::getAnonymousUser()
        )
    );
    $XW->writeElement("releasedresourcecount", (string)$ReleasedResourceCount);
    $XW->writeElement("ratingcount", (string)$RFactory->getRatedRecordCount());

    $ClassFactory = new ClassificationFactory();
    $XW->writeElement("classificationcount", (string)$ClassFactory->getItemCount());

    $SampleCount = $RFactory->getItemCount(
        "INSTR(Description, '[--SAMPLE RECORD--]') > 0"
    );
    $XW->writeElement("sampleresourcecount", (string)$SampleCount);

    $SearchEngine = new SearchEngine();
    $XW->writeElement("searchtermcount", (string)$SearchEngine->searchTermCount());
    $XW->endElement();

    # retrieve and add operating environment info
    $XW->startElement("environment");
    $XW->writeElement("httpserver", $_SERVER["SERVER_SOFTWARE"]);
    $PhpInfo = StdLib::getPhpInfo();
    $XW->writeElement("osstamp", $PhpInfo[""]["System"][0]);
    # (PHP configuration)
    $XW->startElement("phpconfig");
    $PhpVersion = phpversion();
    if ($PhpVersion === false) {
        $PhpVersion = "(unknown)";
    }
    $XW->writeElement("version", $PhpVersion);
    $Settings = array(
        "safe_mode",
        "register_globals",
        "max_execution_time",
        "memory_limit",
        "post_max_size",
        "file_uploads",
        "upload_max_filesize",
    );
    foreach ($Settings as $Setting) {
        $Value = ini_get($Setting);
        if ($Value === false) {
            $Value = "(unavailable)";
        } elseif ($Value == "") {
            $Value = "Off";
        } elseif ($Value == "1") {
            $Value = "On";
        }
        $ElementName = str_replace("_", "", $Setting);
        $XW->writeElement($ElementName, $Value);
    }
    $Val = (isset($PhpInfo["gd"]["GD Version"][0])) ?
        $PhpInfo["gd"]["GD Version"][0] : "unavailable";
    $XW->writeElement("gdversion", $Val);
    $Val = (isset($PhpInfo["gd"]["PNG Support"][0])) ?
        $PhpInfo["gd"]["PNG Support"][0] : "unavailable";
    $XW->writeElement("gdpngsupport", $Val);
    $Val = (isset($PhpInfo["gd"]["JPG Support"][0])) ?
        $PhpInfo["gd"]["JPG Support"][0] : "unavailable";
    $XW->writeElement("gdjpgsupport", $Val);
    $Val = (isset($PhpInfo["gd"]["GIF Support"][0])) ?
        $PhpInfo["gd"]["GIF Support"][0] : "unavailable";
    $XW->writeElement("gdgifsupport", $Val);
    $XW->endElement();
    # (MySQL configuration)
    $DB = new Database();
    $XW->startElement("mysqlconfig");
    $XW->writeElement("clientversion", $DB->getClientVersion());
    $XW->writeElement("serverversion", $DB->getServerVersion());
    $XW->writeElement("connectiontype", $DB->getHostInfo());
    $XW->endElement();
    $XW->endElement();

    $XW->writeElement("comments", $Comments ?? "");

    # retrieve XML from XML stream and return to caller
    $XW->endElement();
    return $XW->outputMemory();
}

# ----- LOCAL FUNCTIONS ------------------------------------------------------

# ----- MAIN -----------------------------------------------------------------

if (!CheckAuthorization(PRIV_SYSADMIN)) {
    return;
}

# assume we're not completed until checking button pushed
$H_Completed = false;

# destination for registration info e-mail
$RegInfoRecipient = "support@metavus.net";

$SysConfig = SystemConfiguration::getInstance();

$FormFields = [
    "ContactName" => [
        "Label" => "Contact Name",
        "Type" => FormUI::FTYPE_TEXT,
        "Required" => true,
        "Value" => $SysConfig->getString("ContactName"),
    ],
    "ContactEmail" => [
        "Label" => "Contact E-mail",
        "Type" => FormUI::FTYPE_TEXT,
        "Required" => true,
        "Value" => $SysConfig->getString("ContactEmail"),
        "ValidateFunction" => array("Metavus\\FormUI", "ValidateEmail"),
    ],
    "Organization" => [
        "Label" => "Organization",
        "Type" => FormUI::FTYPE_TEXT,
        "Value" => $SysConfig->getString("Organization"),
    ],
    "OrganizationType" => [
        "Label" => "Organization Type",
        "Type" => FormUI::FTYPE_OPTION,
        "Options" => [
            "Educational" => "Educational",
            "Non-Profit" => "Non-Profit",
            "Commercial" => "Commercial",
            "Personal" => "Personal",
            "Other" => "Other",
        ],
        "Value" => $SysConfig->isSet("OrganizationType")
                ? $SysConfig->getString("OrganizationType") : "(not set)",
    ],
    "SiteType" => [
        "Label" => "Site Type",
        "Type" => FormUI::FTYPE_OPTION,
        "Options" => [
            "Public" => "Public",
            "Private" => "Private",
            "Intranet" => "Intranet",
            "Other" => "Other",
        ],
        "Value" => $SysConfig->isSet("SiteType")
                ? $SysConfig->getString("SiteType") : "(not set)",
    ],
    "Comments" => [
        "Label" => "Optional Comments",
        "Type" => FormUI::FTYPE_PARAGRAPH,
    ],
    "OkayToList" => [
        "Label" => "Okay to List?",
        "Type" => FormUI::FTYPE_OPTION,
        "Options" => [
            1 => "It is okay to include my site in a public directory of Metavus sites",
            0 => "It is not okay to list my site"
        ],
        "Required" => true,
        "Value" => $SysConfig->getBool("OkayToListSite") ? 1 : 0,
    ]
];

$H_FormUI = new FormUI($FormFields);

$ButtonPushed = StdLib::getFormValue("Submit");
switch ($ButtonPushed) {
    case "Send Registration":
        # check values and bail out if any are invalid
        # no validation functions yet
        if ($H_FormUI->validateFieldInput()) {
            return;
        }

        # retrieve form values
        $NewValues = $H_FormUI->getNewValuesFromForm();

        # set system config values from form
        $SysConfig->setString("ContactName", $NewValues["ContactName"]);
        $SysConfig->setString("ContactEmail", $NewValues["ContactEmail"]);

        if (strlen($NewValues["Organization"])) {
            $SysConfig->setString("Organization", $NewValues["Organization"]);
        }

        $SysConfig->setString("OrganizationType", $NewValues["OrganizationType"]);
        $SysConfig->setString("SiteType", $NewValues["SiteType"]);

        $SysConfig->setBool("OkayToListSite", boolval($NewValues["OkayToList"]));

        # generate XML containing registration info
        $MsgContent = getRegistrationXML($NewValues["Comments"]);

        # email registration info to scout
        $MsgSubject = "Metavus Registration";
        if ($SysConfig->getString("PortalName") != "") {
            $MsgSubject .= " (".$SysConfig->getString("PortalName").")";
        } else {
            $MsgSubject .= " (".$_SERVER["SERVER_NAME"].")";
        }

        $Msg = new Email();
        $Msg->to($RegInfoRecipient);
        $Msg->from($SysConfig->getString("AdminEmail"));
        $Msg->subject($MsgSubject);
        $Msg->body($MsgContent);
        $MailSent = $Msg->send();

        if ($MailSent) {
            $H_Completed = true;
            (ApplicationFramework::getInstance())->logMessage(
                ApplicationFramework::LOGLVL_INFO,
                "Registration sent for version ".METAVUS_VERSION."."
            );
        } else {
            $H_ErrorMsg = "Registration email failed to send.";
        }
        break;
}
